//
//  MoreViewController.m
//  华康通
//
//  Created by  雷雨 on 2017/5/3.
//  Copyright © 2017年 com.huakang. All rights reserved.
//

#import "MoreViewController.h"
#import "AmendKeyController.h"
#import "UMMobClick/MobClick.h"
#import <StoreKit/SKStoreReviewController.h>
#import "DLWTH5Controller.h"

@interface MoreViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSArray* leftArray;
@property (nonatomic, strong) UILabel* myLabel;

@end

@implementation MoreViewController

- (UILabel*)myLabel
{
    if (!_myLabel)
    {
        _myLabel = [[UILabel alloc]initWithFrame:CGRectMake((UISCREENWEITH - 180)/2, ((UISCREENHEIGHT - 40)/2) - 100, 180, 40)];
        _myLabel.textAlignment = NSTextAlignmentCenter;
        
        _myLabel.font = [UIFont systemFontOfSize:15.0];
        _myLabel.textColor = FFFFFFColor;
        _myLabel.backgroundColor = YYColor;
        _myLabel.alpha = 0.7;
        _myLabel.layer.cornerRadius = 20.0;
        _myLabel.layer.masksToBounds = YES;
    }
    return _myLabel;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.leftArray = @[@"常见问题",@"清除缓存",@"检查更新"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:LoadImage(@"back1") style:UIBarButtonItemStylePlain target:self action:@selector(popRootVC)];
    self.title = @"更多";
//    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
}

- (void)popRootVC
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    [MobClick beginLogPageView:@"MoreViewController"];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [MobClick endLogPageView:@"MoreViewController"];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.leftArray.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }
    cell.contentView.backgroundColor = cell.selected ? [UIColor colorWithRed:255.0/255.0 green:212.0/255.0 blue:204.0/255.0 alpha:1.0] : FFFFFFColor;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.textLabel.text = self.leftArray[indexPath.row];
    cell.textLabel.font = SetFont(15);
    if (indexPath.row == 2)
    {
        //获取系统的版本号
        NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        cell.detailTextLabel.text = [NSString stringWithFormat:@"版本号:%@",version];
        cell.detailTextLabel.font = SetFont(13);
    }
    [cell setAccessoryType:UITableViewCellAccessoryNone];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && indexPath.row == 0)
    {
        DLWTH5Controller* h5 = [[DLWTH5Controller alloc]initWithNibName:@"DLWTH5Controller" bundle:nil];
        h5.html = [NSString stringWithFormat:@"%@/static/faq/index.html",DLWTURL];
        h5.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:h5 animated:YES];
//        AmendKeyController* amendKeyVC=[[AmendKeyController alloc]initWithNibName:@"AmendKeyController" bundle:nil];
//        [self.navigationController pushViewController:amendKeyVC animated:YES];
    }
    else if (indexPath.section == 0 && indexPath.row == 1)
    {
        //清除缓存
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *filePath = [paths lastObject];
        NSInteger i = (NSInteger)[self folderSizeAtPath:filePath];
        if (i > 0)
        {
            CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
            TextStatusView *customView  = [TextStatusView view];
            customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
            customView.bottomLabel.text = [NSString stringWithFormat:@"缓存大小为%.2lfM，确定要清理缓存吗？",[self folderSizeAtPath:filePath]];
            [alertView setContainerView:customView];
            [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"暂不清除",@"清除",nil]];
            [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
                switch (buttonIndex)
                {
                    case 0:
                        return ;
                        break;
                    default:
                        [self clearCache:filePath];
                        break;
                }
            }];
            [alertView show];
        }
        else
        {
            ShowAlertViewWithYes(@"还没有产生缓存，无须清理！");
        }
    }
}

//系统提示框
- (void)presentAlerControllerWithMessage:(NSString*)message
{
    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    TextStatusView *customView  = [TextStatusView view];
    customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
    customView.bottomLabel.text = message;
    [alertView setContainerView:customView];
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"好的", nil]];
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
        switch (buttonIndex)
        {
            case 0:
                return ;
                break;
            default:
                return;
                break;
        }
    }];
    [alertView show];
}

//计算单个文件大小
- (float)fileSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path])
    {
        long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size/1024.0/1024.0;
    }
    else
        return 0;
}
//计算目录大小
- (float)folderSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    float folderSize = 0.0;
    if ([fileManager fileExistsAtPath:path])
    {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles)
        {
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            folderSize +=[self fileSizeAtPath:absolutePath];
        }
        //SDWebImage框架自身计算缓存的实现
        //        folderSize+=[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
        return folderSize;
    }
    else
        return 0;
}
//清理缓存文件
- (void)clearCache:(NSString *)path
{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:path])
    {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles)
        {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
        }
    }
    
    [self showLabelWithAnimation];
    
    [[SDImageCache sharedImageCache] cleanDisk];
}

- (void)showLabelWithAnimation
{
    self.myLabel.text = @"正在清理...";
    CABasicAnimation * aniScale = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    aniScale.fromValue = [NSNumber numberWithFloat:0.3];
    aniScale.toValue = [NSNumber numberWithFloat:1.0];
    aniScale.duration = 0.5;
    aniScale.removedOnCompletion = NO;
    [self.myLabel.layer addAnimation:aniScale forKey:nil];
    [self.view addSubview:self.myLabel];
    //动画删除label
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC));
    dispatch_after(delay, dispatch_get_main_queue(), ^{
        self.myLabel.text = @"清理完成!";
        dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC));
        dispatch_after(delay, dispatch_get_main_queue(), ^{
            [self.myLabel removeFromSuperview];
        });
    });
    
}

@end
